package com.yzd.crm.dao.impl;

import com.yzd.crm.dao.CustomerDao;
import com.yzd.crm.domain.BaseDict;
import com.yzd.crm.domain.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Auther: Ye Zhengdong
 * @Date: 2019/4/3 11:28
 * @Description:
 */
@Repository
public class CustomerDaoImpl implements CustomerDao {

//    @Override
//    public void addCustomer(Customer customer) {
//        Configuration cfg = new Configuration().configure();
//        SessionFactory factory = cfg.buildSessionFactory();
//        Session session = factory.openSession();
//        Transaction transaction = session.beginTransaction();
//        session.save(customer);
//        transaction.commit();
//        session.close();
//    }

    @Autowired
    private HibernateTemplate hibernateTemplate;

    @Override
    public void addCustomer(Customer customer) {
        hibernateTemplate.save(customer);
    }

    @Override
    public List<BaseDict> findLevel(String code) {
        return (List<BaseDict>) hibernateTemplate.find("from BaseDict where dict_type_code = ?", code);
    }

    @Override
    public List<BaseDict> findSource(String code) {
        return (List<BaseDict>) hibernateTemplate.find("from BaseDict where dict_type_code = ?", code);
    }

    @Override
    public List<BaseDict> findIndustry(String code) {
        return(List<BaseDict>) hibernateTemplate.find("from BaseDict where dict_type_code = ?", code);
    }

    @Override
    public void save(Customer customer) {
        hibernateTemplate.save(customer);
    }

    @Override
    public List<Customer> findAll() {
        return (List<Customer>) hibernateTemplate.find("from Customer");
    }

    @Override
    public List<Customer> conditionFind(DetachedCriteria dc) {
        return (List<Customer>) hibernateTemplate.findByCriteria(dc);
    }

    @Override
    public Customer findById(Integer id) {
        //return (Customer) hibernateTemplate.find("from Customer where custId = ?", id).get(0);
        return hibernateTemplate.get(Customer.class, id);
    }

    @Override
    public void update(Customer customer) {
        hibernateTemplate.update(customer);
    }

    @Override
    public void delete(Customer customer) {
        hibernateTemplate.delete(customer);
    }
}
